//
//  YMRequest.swift
//  ChengLuMall
//
//  Created by 吳梓杭 on 2023/5/28.
//

import Foundation
import Alamofire
import Moya
import SwiftyJSON

extension YMTargetType {
    
    @discardableResult
    public func request(success: APISuccess, failure: APIFailure = nil, progress: ProgressBlock? = nil) -> Moya.Cancellable? {
        
        let tuple = YMNetworkUtil.handyConfigurationPlugin(self.plugins, target: MultiTarget.target(self))
        if tuple.endRequest, let result = tuple.result {
            YMNetworkUtil.handleResult(result, isParser: self.isParser, success: success, failure: failure, progress: progress)
            return nil
        }
        
        let session = tuple.session ?? {
            let configuration = URLSessionConfiguration.af.default
            configuration.headers = Alamofire.HTTPHeaders.default
            configuration.timeoutIntervalForRequest = YMNetworkConfig.timeoutInterval
            return Moya.Session(configuration: configuration, startRequestsImmediately: false)
        }()
        
        let queue = DispatchQueue(label: "condy.request.network.queue", qos: .background, attributes: [.concurrent])
        let provider = MoyaProvider<MultiTarget>(stubClosure: { _ in
            return .never
        }, callbackQueue: queue, session: session, plugins: self.plugins)
        
        // 先抛出本地数据
        switch tuple.result {
        case .success(let response):
            let json = JSON(response.data)
            let responseModel = YMResponse.init(json: json)
            if responseModel.code == 200 {
                success?(responseModel)
            }
            break
        default:
            break
        }

        return YMNetworkUtil.beginRequest(self, base: provider, queue: queue, success: { response in
            JJMainAsync {
                requestSuccess(response, success: success, failure: failure)
            }
        }, failure: { response, error in
            JJMainAsync {
                requestFailed(response, error)
                failure?(response, error)
            }
        }, progress: progress)

    }

    private func requestSuccess(_ response: YMResponse, success: APISuccess, failure: APIFailure) -> Void {
        if !self.isForbidPrint {
            let URL = self.baseURL.absoluteString + self.path
            //        print(message: "\(self.method.rawValue)请求成功\n URL:\(URL)\n Headers:\(JSON(self.headers ?? Any.self))\n Parameters:\(JSON(self.parameters))\n responseObject:\(response.outsideJson)\n")
            print(message: "\(self.method.rawValue)请求成功\n URL:\(URL)\n Parameters:\(JSON(self.parameters))\n responseObject:\(response.outsideJson)\n")
        }
        success?(response)
    }
    
    private func requestFailed(_ response: YMResponse, _ error: Swift.Error) -> Void {
        if !self.isForbidPrint {
            let URL = self.baseURL.absoluteString + self.path
            //        print(message: "\(self.method.rawValue)请求失败\n URL:\(URL)\n Headers:\(JSON(self.headers ?? Any.self))\n Parameters:\(JSON(self.parameters))\n responseObject:\(response.outsideJson)\n")
            print(message: "\(self.method.rawValue)请求失败\n URL:\(URL)\n Parameters:\(JSON(self.parameters))\n responseObject:\(response.outsideJson)\n")
            let data = (error as NSError).userInfo["com.alamofire.serialization.response.error.data"]
            if data == nil {
                return
            }
            let errorString = String(data: data as! Data, encoding: String.Encoding.utf8) ?? ""
            print(message: "\(self.method)错误信息\n URL:\(URL)\n error:\(errorString)\n")
        }
    }
    
}
